package concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther hanchao
 * @date 2017/3/13 16:08
 */
public class ConditionTest {
    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args){
        Condition condition = lock.newCondition();

        Thread a = new Thread(){
            @Override
            public void run() {
                try {
                    lock.lock();
                    System.out.println("等一个信号");
                    condition.await();
                } catch(Exception e){
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
                System.out.println("拿到一个信号");
            }
        };
        a.start();


        Thread b = new Thread(){
            @Override
            public void run() {
                try {
                    lock.lock();
                    System.out.println("我拿到锁了");
                    Thread.sleep(2000);
                    condition.signalAll();
                    System.out.println("发出了一个信号");
                } catch(Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        };
        b.start();

/*        运行结果
        等一个信号
        我拿到锁了 2s 以后
        发出了一个信号
        拿到一个信号*/
//执行await，会释放锁，然后沉睡(挂起)，等待唤醒
        //类似wait,notify的机制
    }

}
